<template>
  <h2 class="text-base font-semibold leading-7 text-gray-900">
    {{ $t('pageFanSpeed.zoneControl') }}
  </h2>
  <el-tabs
    tab-position="left"
    style="height: 200px"
    class="demo-tabs mt-7 mb-7"
  >
    <el-tab-pane
      v-for="(zoneInfo, index) in zoneInfos"
      :key="index"
      :label="zoneInfo.ZoneName"
    >
      <el-form :model="form" :rules="rules">
        <span> {{ $t('pageFanSpeed.mode') }}</span>
        <el-select
          class="ml-5"
          v-model="zoneInfo.Current"
          placeholder="Select"
          size="large"
          style="width: 240px"
        >
          <el-option
            v-for="option in zoneInfo.Supported"
            :key="option"
            :value="option"
          />
        </el-select>
        <el-popconfirm
          :title="
            $t('pageFanSpeed.modal.confirmMessage', {
              zoneName: zoneInfo.ZoneName,
            })
          "
          @confirm="submitForm(zoneInfo, pwmValues)"
        >
          <template #reference>
            <el-button class="ml-10 submit-button">{{
              $t('global.action.save')
            }}</el-button>
          </template>
        </el-popconfirm>
        <template v-if="zoneInfo.Current === zoneInfo.Supported[0]">
          <el-row
            class="mt-5"
            v-for="(fanList, key, index1) in zoneInfo.FanInfo"
            :key="index1"
          >
            <el-col :span="6">
              <el-row>
                <span>{{ key }}</span>
                <el-form-item :prop="`pwmValues.${key}`">
                  <el-input
                    class="ml-5 w-20"
                    v-model="form.pwmValues[key]"
                  ></el-input>
                </el-form-item>
              </el-row>
            </el-col>
            <el-col :span="6">
              <el-row v-for="(fan, index2) in fanList" :key="index2">
                {{ fan }}
                <span class="ml-10">{{ fanSpeeds[fan] }}</span>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-form>
    </el-tab-pane>
  </el-tabs>
  <h2 class="text-base font-semibold leading-7 text-gray-900 mb-6">
    {{ $t('pageFanSpeed.currentStatus') }}
  </h2>
  <fan-speed-chart :fan-speeds="fanSpeeds" />
</template>

<script setup lang="ts">
import { useFanSpeedStore } from '@/store/SystemManagement/FanSpeed/FanSpeedStore';
import fanSpeedChart from './FanSpeedChart.vue';
import { useI18n } from 'vue-i18n';
import useVuelidateTool from '@/hooks/useVuelidateTool';

const i18n = reactive(useI18n());

const { useVuelidate, required, between, elementInputValidator, numeric } =
  useVuelidateTool();

const fanSpeedStore = useFanSpeedStore();
await fanSpeedStore.getFanAllData().catch((err) => {
  throw err;
});

const zoneInfos = computed(() => fanSpeedStore.zoneInfos);
const pwmValues = computed(() => fanSpeedStore.pwmValues);
const fanSpeeds = computed(() => fanSpeedStore.fanSpeeds);

const form = reactive({
  pwmValues: pwmValues.value,
});

// Set v$.
const pwm = {} as { [index: string]: any };
Object.keys(pwmValues.value).forEach((fanName) => {
  pwm[fanName] = {
    required,
    numeric,
    between: between(0, 100),
  };
});

const v$ = useVuelidate(
  {
    pwmValues: pwm,
  },
  form,
);

// Set rules.
const pwm2 = {} as { [index: string]: any };
Object.keys(pwmValues.value).forEach((fanName) => {
  pwm2[fanName] = [
    {
      trigger: 'blur',
      validator: elementInputValidator.value(v$, `pwmValues.${fanName}`),
    },
  ];
});

const rules = computed(() => {
  return {
    pwmValues: pwm2,
  };
});

const submitForm = (
  zoneInfo: { [index: string]: any },
  pwmValues: { [index: string]: number | string },
) => {
  v$.value.$touch();
  if (v$.value.$invalid) {
    return;
  }
  for (let pwmName in pwmValues) {
    if (typeof pwmValues[pwmName] == 'string') {
      pwmValues[pwmName] = parseInt(pwmValues[pwmName] as string);
    }
  }
  fanSpeedStore
    .manualControl({
      zoneInfo,
      pwmValues,
    })
    .then(() => {
      // Successfully
      ElNotification({
        title: 'Success',
        message: i18n.t('pageFanSpeed.toast.successSaving'),
        type: 'success',
      });
    })
    .catch(() => {
      // Set failed.
      ElNotification({
        title: 'Error',
        message: i18n.t('pageFanSpeed.toast.errorSetting'),
        type: 'error',
      });
    })
    .finally(() => {
      // After operations get fan data again.
      fanSpeedStore.getFanAllData();
    });
};
</script>

<style lang="scss"></style>
